import time
import os
from selenium import webdriver
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
import datetime
from email.header import Header
from openpyxl import load_workbook
import urllib.request
import gzip
import json
#浏览器环境配置
chromedriver = "C:\\Program Files (x86)\\Google\Chrome\\Application"
os.environ["webdriver.ie.driver"] = chromedriver





def get_info():
    username = []
    password = []
    qq = [] #申明list
    city = []
    idea = []
    wb = load_workbook(filename='D:\\3.xlsx') #导入工作表
    sheetnames = wb.get_sheet_names() #获得表单名字
    sheet = wb.get_sheet_by_name(sheetnames[0]) #从工作表中提取某一表单
    row = wb[sheetnames[0]].max_row
    for rowNum in range(2,row+1):
        username.append(sheet.cell(row=rowNum,column=9).value) #获得数据
        password.append(sheet.cell(row=rowNum,column=10).value)
        qq.append(sheet.cell(row=rowNum,column=8).value)
        idea.append(sheet.cell(row=rowNum,column=11).value)
        city.append(sheet.cell(row=rowNum,column=6).value)
    return username, password, qq, idea, city
def get_str_btw(s, f, b):
    par = s.partition(f)
    return (par[2].partition(b))[0][:]


def get_weather_data(city) :
    city_name = city
    url1 = 'http://wthrcdn.etouch.cn/weather_mini?city='+urllib.parse.quote(city_name)
    #print(url1)
    weather_data = urllib.request.urlopen(url1).read()
    #读取网页数据
    weather_data = gzip.decompress(weather_data).decode('utf-8')
    #解压网页数据
    weather_dict = json.loads(weather_data)
    #将json数据转换为dict数据
    if weather_dict.get('desc') == 'invilad-citykey':
        print('你输入的城市名有误，或者天气中心未收录你所在城市')
        result = '城市有误'
    elif weather_dict.get('desc') =='OK':
        forecast = weather_dict.get('data').get('forecast')
        result = "城市："+weather_dict.get('data').get('city')+'\n天气：'+forecast[0].get('type')+'\n温度：'+weather_dict.get('data').get('wendu')+'℃ '+'\n感冒：'+weather_dict.get('data').get('ganmao')+'\n高温：'+forecast[0].get('high')+'\n低温：'+forecast[0].get('low')
    #     print('城市：',weather_dict.get('data').get('city'))
    #     print('温度：',weather_dict.get('data').get('wendu')+'℃ ')
    #     print('感冒：',weather_dict.get('data').get('ganmao'))
    #     print('风向：',forecast[0].get('fengxiang'))
    #     print('风级：',forecast[0].get('fengli'))
    #     print('高温：',forecast[0].get('high'))
    #     print('低温：',forecast[0].get('low'))
    #     print('天气：',forecast[0].get('type'))
    #     print('日期：',forecast[0].get('date'))
    #     print('*******************************')
    # print('***********************************')
    print('天气信息获取成功')
    # print(result)
    return result



def bao(username, password, qq, idea,city):
    finshed = 0 #初始化数据
    sum = len(username)
    print('账号密码读取成功，共',sum,'人')

    #打开浏览器
    driver=webdriver.Chrome() 
    driver.get('http://yiqing.ctgu.edu.cn/wx/health/main.do')

    #尝试报平安
    try:
        for x in range(0,sum):       
            driver.find_element_by_id('username1').click() #点击用户名输入框
            driver.find_element_by_id('username1').clear() #清空输入框
            driver.find_element_by_id('username1').send_keys(username[x]) #自动敲入用户名
            driver.find_element_by_id('password1').click() #点击密码输入框
            driver.find_element_by_id('password1').clear() #清空输入框
            driver.find_element_by_id('password1').send_keys(password[x]) #自动敲入密码
            driver.find_element_by_xpath('/html/body/main/section[2]/form/div[3]/input').click() #点击登陆
            time.sleep(2)
            #判断是是否密码错误
            try:
                state0 = driver.find_element_by_id('msg')
                print('用户'+str(username[x])+'密码错误，请检查该用户密码后重试!\n')
                continue               
            except:
                print('用户'+str(username[x])+'登陆成功')
                    
            #班委不一样,先切换角色
            s = driver.find_elements_by_id('menu_wjdc')#为什么能找到我也不清楚
            if len(s) != 0:
                print('该用户是班委')
                driver.find_element_by_id('menu_my').click() #点击我的按钮
                time.sleep(1)                
                driver.find_element_by_id('change_btn').click()#点击切换角色
                time.sleep(1)
                driver.find_element_by_xpath('/html/body/main/div[2]/section/form/div/div/div/div/label[2]').click()#点击学生
                driver.find_element_by_xpath('/html/body/main/div[2]/div/button').click()#点击确定
                time.sleep(5)  
            else:
                pass
            driver.find_element_by_xpath('/html/body/main/section/header/div[2]/button').click() #点击报平安
            # 尝试保平安，因为可能已经报过了
            try:
                driver.find_element_by_xpath('/html/body/main/div[1]/button').click()#点击报平安
                time.sleep(2)
                driver.find_element_by_xpath('/html/body/div[2]/div[3]/a[2]').click() #点击提交
                time.sleep(1)
                if idea[x] == '愿意':#判断有没有填邮箱 
                    try:
                        time.sleep(3)         
                        driver.get_screenshot_as_file(u"baopingan.png")#保存截图
                        city1 = get_str_btw(city[x],'-',r")")
                        print(city1)
                        wea_info = get_weather_data(city1)
                        send(str(qq[x])+'@qq.com',wea_info)#发邮件通知每个人
                        print('用户'+str(username[x])+'的邮箱'+str(qq[x])+'@qq.com发送成功')
                        time.sleep(1)                        
                    except :
                        print('用户'+str(username[x])+'的邮箱'+str(qq[x])+'@qq.com发送失败')
                else:
                    print('用户'+str(username[x])+'未填写邮箱，未发送邮件')
            except:
                pass
            time.sleep(2)
            state1 = driver.find_element_by_xpath('/html/body/main/section/header/div[1]/span').text #判断是否报成功
            state2 = driver.find_element_by_xpath('/html/body/main/section/header/div[1]').text #获取真实名字
            if state1 == '今日已上报':
                print('用户'+str(username[x])+state2+'\n')
                finshed += 1
            else:
                print('用户',str(username[x]),'报平安失败，请重新上报')
                continue
            driver.find_element_by_id('menu_my').click() #点击我的按钮
            time.sleep(1)
            driver.find_element_by_id('submit_btn').click() #点击退出登录
            time.sleep(1)
        print('\n*****应报'+str(sum)+'人'+'实报'+str(finshed)+'人'+'请查收！*****')
    # 不管有没成功，都发邮件
    finally:
        if sum == finshed:
            msg = '应报'+str(sum)+'人'+'实报'+str(finshed)+'人'+'请查收！'
            head = '安全上报成功'
        else:
            msg = '应报'+str(sum)+'人'+'实报'+str(finshed)+'人'+'请检查服务器！'
            head = '安全上报失败'
                
        send_rusult(head,msg)#发邮件给作者反馈结果
        driver.close()
    return msg,head

def send(to_addr,wea_info):
    nowtime = datetime.datetime.now().strftime('%m-%d')#获取当前时间
    # 发信方的信息：发信邮箱，邮箱授权码
    from_addr = ''#邮箱
    password = ''  #授权码
    # 收信方邮箱
    to_addr = to_addr
    subject = nowtime+"安全上报已成功！"  # 主题
    msg = MIMEMultipart('related')

    html = '<html><body><div>'+wea_info+'<div><div><img src="cid:imageid" alt="imageid"></div></body></html>'

    msgText = MIMEText(html,'html', 'utf-8')  # 正文
    # msg = MIMEText(content)
    msg.attach(msgText)
    msg['Subject'] = subject
    msg['From'] = from_addr
    msg['To'] = to_addr
 
    file = open("baopingan.png", "rb")
    img_data = file.read()
    file.close()
 
    img = MIMEImage(img_data)
    img.add_header('Content-ID', 'imageid')
    msg.attach(img)
 
    # try:
    s = smtplib.SMTP_SSL("smtp.163.com",994)  # 邮件服务器及端口号
    s.login(from_addr, password)
    s.sendmail(from_addr, to_addr, msg.as_string())
    s.quit()

# 这个应该是可以和上面合并的，写的多余了
def send_rusult(head,text,):
    nowtime = datetime.datetime.now().strftime('%m-%d')#获取当前时间
    msg_from=''#发送方邮箱
    passwd='' #填入发送方邮箱的授权码
    msg_to='' #收件人邮箱
                                
    subject= head#主题     
    content= text+'\n'+nowtime
    msg = MIMEText(content)
    msg['Subject'] = subject
    msg['From'] = msg_from
    msg['To'] = msg_to

    s = smtplib.SMTP_SSL("smtp.163.com",994)
    s.login(msg_from, passwd)
    s.sendmail(msg_from, msg_to, msg.as_string())
    print ("发送结果成功")
    s.quit()

def main():
    nowtime = datetime.datetime.now().strftime('%m-%d')#获取当前时间
    print('\n','***Write By 盛意以山河***','\n')
    print('今天是'+nowtime)
    username, password, qq, idea,city = get_info()
    bao(username, password, qq, idea,city)

if __name__ == "__main__":
    main()

